package com.czk.socket;

import org.junit.Test;

import java.nio.ByteBuffer;
import java.nio.channels.Pipe;

/**
 * pipe的demo
 *
 * @Author:ChenZhangKun
 * @Date: 2021/1/10 12:39
 */
public class PipeTest {
    @Test
    public void test1() throws Exception {
        // 获取管道
        Pipe pipe = Pipe.open();
        // 创建缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        // 获取写管道
        Pipe.SinkChannel sink = pipe.sink();
        byteBuffer.put("czk".getBytes());
        // 写入数据
        byteBuffer.flip();
        sink.write(byteBuffer);

        // 获取资源管道
        Pipe.SourceChannel source = pipe.source();
        // 刷新
        byteBuffer.flip();
        // 读取
        int len = source.read(byteBuffer);
        System.out.println(new String(byteBuffer.array(), 0, len));
        source.close();

        sink.close();
    }
}
